/****
	Copyright 2011 Taras Kulbachka

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package com.atdevsoft.apps.abyss;

import java.io.File;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper{

	public static final String DATABASE_NAME = "abyss.db";
	private static final int DATABASE_VERSION = 1;
	public static final String TABLE_NAME_QUOTES = "quotes";	
	
	public static final String QUOTES_ID = "_id";
	public static final String QUOTES_BASH_ID = "bash_id";
	public static final String QUOTES_POSTED = "posted";
	public static final String QUOTES_QUOTE = "quote";
	
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	@Override
	public SQLiteDatabase getWritableDatabase()
	{
		SQLiteDatabase db = null;
		while (db == null)
		{
			try
			{
				File sdDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/abyss/");
				sdDir.mkdirs();
				Log.d("abyss db", sdDir.getAbsolutePath());
				File dbFile = new File(sdDir, "data.sqlite");
				Log.d("abyss db", dbFile.getAbsolutePath());


				db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
				onCreate(db);
			}
			catch(SQLiteException e)
			{
				try {					
					Thread.sleep(500);
				} catch (InterruptedException e1) {
				}
			}	
		}
		return db;
		
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(quotesCreate());		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME_QUOTES);		
		onCreate(db);
	}
	
	private String quotesCreate()
	{
		StringBuilder result = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
		result.append(TABLE_NAME_QUOTES);
		result.append(" (");
		result.append(QUOTES_ID);
		result.append(" INTEGER PRIMARY KEY, ");
		result.append(QUOTES_BASH_ID);
		result.append(" INTEGER, ");		
		result.append(QUOTES_POSTED);
		result.append(" TEXT, ");
		result.append(QUOTES_QUOTE);
		result.append(" TEXT);");
		return result.toString();
	}
}
